{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UvTPRErEO2cl"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "LCJL7_hQO3jW"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sP8PQnz1QrcF"
      },
      "source": [
        "# Gemini API: Sentiment Analysis"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bxGr_x3MRA0z"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/json_capabilities/Sentiment_Analysis.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ysy--KfNRrCq"
      },
      "source": [
        "You will use the Gemini to extract sentiment scores of reviews."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ne-3gnXqR0hI"
      },
      "outputs": [],
      "source": [
        "%pip install -U -q \"google-genai>=1.0.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eomJzCa6lb90"
      },
      "source": [
        "## Configure your API key\n",
        "\n",
        "To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "v-JZzORUpVR2"
      },
      "outputs": [],
      "source": [
        "from google.colab import userdata\n",
        "from google import genai\n",
        "\n",
        "GOOGLE_API_KEY = userdata.get('GOOGLE_API_KEY')\n",
        "client = genai.Client(api_key=GOOGLE_API_KEY)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R3EUoLgJNfe7"
      },
      "source": [
        "## Example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cblGFW3VwzyO"
      },
      "source": [
        "Start by defining how you want your JSON to be returned and which categories you would like to classify an item by. After that, go ahead and define some examples. In this case, you are trying to classify reviews as positive, neutral, or negative."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QGdJnd0AOKbu"
      },
      "outputs": [],
      "source": [
        "import enum\n",
        "from typing_extensions import TypedDict\n",
        "\n",
        "\n",
        "class Magnitude(enum.Enum):\n",
        "  WEAK = \"weak\"\n",
        "  STRONG = \"strong\"\n",
        "\n",
        "\n",
        "class Sentiment(TypedDict):\n",
        "  positive_sentiment_score: Magnitude\n",
        "  negative_sentiment_score: Magnitude\n",
        "  neutral_sentiment_score: Magnitude\n",
        "\n",
        "\n",
        "system_instruct = \"\"\"\n",
        "Generate each sentiment score probability (positive, negative, or neutral) for the whole text.\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yRq9PGpVQLUK"
      },
      "outputs": [],
      "source": [
        "negative_review = \"This establishment is an insult to the culinary arts, with inedible food that left me questioning the chef's sanity and the health inspector's judgment.\"\n",
        "positive_review = \"This restaurant is a true gem with impeccable service and a menu that tantalizes the taste buds. Every dish is a culinary masterpiece, crafted with fresh ingredients and bursting with flavor.\"\n",
        "neutral_review = \"The restaurant offers a decent dining experience with average food and service, making it a passable choice for a casual meal.\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z0yHqEJRwp_U"
      },
      "source": [
        "Take a look at each of the probabilities returned to see how each of these reviews would be classified by the Gemini model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RGgPk_Lk-EV5"
      },
      "source": [
        "Helper function to generate content from sentiment llm:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oCBC8pNy-Ply"
      },
      "outputs": [],
      "source": [
        "from google.genai import types\n",
        "\n",
        "def generate_content(review):\n",
        "    MODEL_ID = \"gemini-2.5-flash\" # @param [\"gemini-2.5-flash-lite\",\"gemini-2.5-flash\",\"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\":true, isTemplate: true}\n",
        "    return client.models.generate_content(\n",
        "        model=MODEL_ID,\n",
        "        contents=review,\n",
        "        config=types.GenerateContentConfig(\n",
        "            system_instruction=system_instruct,\n",
        "            response_mime_type=\"application/json\",\n",
        "            response_schema=Sentiment,\n",
        "        )\n",
        "    )"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Tz0cDFyD9uUT"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'negative_sentiment_score': <Magnitude.STRONG: 'strong'>,\n",
            " 'neutral_sentiment_score': <Magnitude.WEAK: 'weak'>,\n",
            " 'positive_sentiment_score': <Magnitude.WEAK: 'weak'>}\n"
          ]
        }
      ],
      "source": [
        "from pprint import pprint\n",
        "\n",
        "response = generate_content(negative_review)\n",
        "pprint(response.parsed)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bMW3QmYy9uUT"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'negative_sentiment_score': <Magnitude.WEAK: 'weak'>,\n",
            " 'neutral_sentiment_score': <Magnitude.WEAK: 'weak'>,\n",
            " 'positive_sentiment_score': <Magnitude.STRONG: 'strong'>}\n"
          ]
        }
      ],
      "source": [
        "response = generate_content(positive_review)\n",
        "pprint(response.parsed)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QTjUYa4J9uUT"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'negative_sentiment_score': <Magnitude.WEAK: 'weak'>,\n",
            " 'neutral_sentiment_score': <Magnitude.STRONG: 'strong'>,\n",
            " 'positive_sentiment_score': <Magnitude.WEAK: 'weak'>}\n"
          ]
        }
      ],
      "source": [
        "response = generate_content(neutral_review)\n",
        "pprint(response.parsed)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AGOx4_7r1uN6"
      },
      "source": [
        "## Summary\n",
        "You have now used the Gemini API to analyze the sentiment of restaurant reviews using structured data. Try out other types of texts, such as comments under a video or emails.\n",
        "\n",
        "Please see the other notebooks in this directory to learn more about how you can use the Gemini API for other JSON related tasks."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Sentiment_Analysis.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
